package cn.tannn.ops.customer.service.impl;


import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import cn.tannn.ops.customer.dao.CustomerDao;
import cn.tannn.ops.customer.dao.RoleCustomerDao;
import cn.tannn.ops.customer.entity.Customer;
import cn.tannn.ops.customer.entity.RoleCustomer;
import cn.tannn.ops.customer.service.RoleCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * 角色-系统用户
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2023/12/4 13:40
 */
@Service
@Slf4j
public class RoleCustomerServiceImpl extends J2ServiceImpl<RoleCustomerDao, RoleCustomer, Long> implements RoleCustomerService {
    private final CustomerDao customerDao;

    public RoleCustomerServiceImpl(CustomerDao customerDao) {
        super(RoleCustomer.class);
        this.customerDao = customerDao;
    }

    @Override
    public List<Long> getUserIdByRoleCode(String roleCode) {
        return getJpaBasicsDao().findUserIdByRoleCode(roleCode);
    }

    @Override
    public List<Long> getUserIdByRoleCode(List<String> roleCode) {
        return getJpaBasicsDao().findUserIdByRoleCodeIn(roleCode);
    }

    @Override
    public List<String> getUserLoginNameByRoleCode(List<String> roleCode) {
        List<Long> userId = getJpaBasicsDao().findUserIdByRoleCodeIn(roleCode);
        return customerDao.findByIdIn(userId).stream().map(Customer::getLoginName).collect(Collectors.toList());
    }

    @Override
    public boolean deleteByRoleCodeAndUserIds(String roleCode, Collection<Long> userIds) {
        try {
            getJpaBasicsDao().deleteByRoleCodeAndUserIdIn(roleCode, userIds);
        } catch (Exception e) {
            log.error("角色-用户删除失败 ===> ", e);
            return false;
        }
        return true;
    }

    @Override
    public List<String> deleteByRoleCode(List<String> roleCodes) {
        try {
            List<Long> userId = getJpaBasicsDao().findUserIdByRoleCodeIn(roleCodes);
            List<String> loginNames = customerDao.findByIdIn(userId).stream().map(Customer::getLoginName).collect(Collectors.toList());
            getJpaBasicsDao().deleteByRoleCodeIn(roleCodes);
            return loginNames;
        } catch (Exception e) {
            log.error("角色-用户删除失败 ==> ", e);
        }
        return Collections.emptyList();
    }


    @Override
    public List<String> getRoleCodeByUserId(Long userId) {
        return getJpaBasicsDao().findRoleCodeByUserId(userId);
    }

    @Override
    public Optional<RoleCustomer> findByRoleAndUser(String roleCode, Long userId) {
        return getJpaBasicsDao().findByUserIdAndRoleCode(userId, roleCode);
    }
}
